from fastapi import Body
# from pydantic import BaseModel, Field
from ..dependencies import router, me, success, depens
from ..models.cart import Cart
from ..models.base import Item, Shop
from ..models.user import Address
from typing import Annotated
from ..services.item import countFee

## 查询购物车商品
@router.get('/cart', tags=['flow'], dependencies=depens())
async def index():
    ### 检测购物车商品是否有变化(价格,库存,上下架),有的话要在购物车更新
    changedItems = [row for row in Cart.select(Item.price, Item.stock, Cart.price, Cart.number).join(Item).where(Cart.user_id==me('id'), (Cart.price!=Item.price | Cart.number>Item.stock)).dicts()]
    items = Cart.select(Cart.id, Cart.name, Cart.price, Cart.thumb, Cart.number, Cart.checked, Cart.shop_id, Shop.name.alias('shop_name')).join(Shop).where(Cart.user_id==me('id')).order_by(Cart.id.desc()).dicts()
    result = countFee(items)
    dict = {}
    for row in result['items']:
        if not row['shop_id'] in dict:
            dict[row['shop_id']] = {'id': row['shop_id'], 'name': row['shop_name'], 'items': []}
        dict[row['shop_id']]['items'].append({k: row[k] for k in ('id', 'name', 'price', 'thumb', 'number', 'checked') if k in row})

    return success({
        'list': list(dict.values()),
        'amount': result['amount'],
        'count': result['count'],
        'total': Cart.select().where(Cart.user_id==me('id')).count(),
        'changedItems': changedItems
    })
## 修改购物车商品
@router.post('/cart', tags=['flow'], dependencies=depens())
async def update(item_id: Annotated[int, Body(embed=True)], number: Annotated[int, Body(embed=True)]):
    if Cart.select().where(Cart.user_id==me('id'), Cart.item_id==item_id).exists():
        model = Cart.update({'number': Cart.number+number}).where(Cart.user_id==me('id'), Cart.item_id==item_id).execute()
    else:
        item = Item.select(Item.name, Item.thumb, Item.price).where(Item.id==item_id).get()
        model = Cart.create(user_id=me('id'), item_id=item_id, **item.__data__)
    return success(model)
## 选中购物车商品
@router.put('/cart/check', tags=['flow'], dependencies=depens())
async def update(ids: Annotated[list[int], Body(embed=True)] = []):
    Cart.update({'checked': 1 - Cart.checked}).where(Cart.id.in_(ids), Cart.user_id==me('id')).execute()
    items = [row for row in Cart.select().where(Cart.user_id==me('id'), Cart.checked==1).dicts()]
    result = countFee(items)
    return success(result)
## 修改购物车商品
@router.put('/cart/{id}', tags=['flow'], dependencies=depens())
async def update(id: int, number: Annotated[int, Body(embed=True)]):
    Cart.update({'number': number}).where(Cart.id==id, Cart.user_id==me('id')).execute()
    items = [row for row in Cart.select().where(Cart.user_id==me('id'), Cart.checked==1).dicts()]
    result = countFee(items)
    return success(result)
## 删除购物车商品
@router.delete('/cart/{id}', tags=['flow'], dependencies=depens())
async def delete(id: int):
    Cart.delete().where(Cart.id == id, Cart.user_id==me('id')).execute()
    return success()
## 购物车下单
@router.get('/checkout', tags=['flow'], dependencies=depens())
async def checkout():
    where = [Cart.user_id==me('id'), Cart.checked==1]
    items = Cart.select(Cart.id, Cart.name, Cart.price, Cart.thumb, Cart.number, Cart.checked, Cart.shop_id, Shop.name.alias('shop_name')).join(Shop).where(*where).order_by(Cart.id.desc()).dicts()
    result = countFee(items)
    dict = {}
    for row in result['items']:
        if not row['shop_id'] in dict:
            dict[row['shop_id']] = {'id': row['shop_id'], 'name': row['shop_name'], 'items': []}
        dict[row['shop_id']]['items'].append({k: row[k] for k in ('id', 'name', 'price', 'thumb', 'number', 'checked') if k in row})
    if Address.select().where(Address.user_id==me('id')).exists():
        address = Address.select().where(Address.user_id==me('id')).order_by(Address.id.desc()).get().__data__
    else:
        address = {}

    return success({
        'list': list(dict.values()),
        'amount': result['amount'],
        'count': result['count'],
        'total': Cart.select().where(*where).count(),
        'address': address
    })
## 直接购买
@router.get('/direct/{id}', tags=['flow'], dependencies=depens())
async def checkout(id: int):
    list = [{'number': 1, **Item.select(Item.id, Item.price, Item.name, Item.thumb).where(Item.id==id).get().__data__}]
    if Address.select().where(Address.user_id==me('id')).exists():
        address = Address.select().where(Address.user_id==me('id')).order_by(Address.id.desc()).get().__data__
    else:
        address = False
    return success({
        'list': list,
        'address': address
    })
